import json
import random,string
from datetime import datetime
from tkinter import messagebox


class MysqlDatabases:
    def __init__(self):
        with open('./info/account.json', 'r', encoding='utf-8') as f:
            self.users = json.load(f)
        with open('./info/volunteers.json', 'r', encoding='utf-8') as f:
            self.volunteers = json.load(f)
        with open('./info/information.json', 'r', encoding='utf-8') as f:
            self.information = json.load(f)
        
    def check_login(self,username,password) :
        for user in self.users :
         if username==user['username']:
            if password == user['password']:
                return True,f"登陆成功，当前登陆用户{username}"
            else:
                return False,f"登陆失败,用户：{username}的密码疑似错误,请检查"

        return False,f"登陆失败,管理员未查询到用户：{username}"
    

    def check_access(self,access,username,doAccess):
        levels = ['min', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'max']
        try:
            doAccess = levels.index(access)
        except ValueError:
            return False, f"你的权限为：{access},不支持启用功能"
        for user in self.users:
            if username == user['username']:
                    user_access_level = user.get('access', 'min')  
                    user_access_index = levels.index(user_access_level)
    
                    if user_access_index >= doAccess:
                        return True, f"用户{username}拥有足够的权限级别：{user_access_level}"
                    else:
                        return False, f"用户{username}的权限级别不足，当前级别：{user_access_level}，需要级别：{access}"
    
        return False, f"查无此人：{username}"

    def all(self):
        return self.volunteers
    def info(self):
        return self.information
    def header_id(self,count):
        return [''.join(random.choices(string.ascii_letters + string.digits, k=14)) + ''.join(random.choices('0123456789abcdef', k=2))for _ in range(count)]  
    def archive_id(self):
        return ''.join(random.choices(string.digits, k=12))
    def save(self):

        with open('volunteers.json','w',encoding='utf-8') as file:
            file.write(json.dumps(self.volunteers,indent=4,ensure_ascii=False))


    def calculate_age(self,person_id):
        try:
            birth_date_str = person_id[6:14]
            # 验证日期字符串是否仅包含数字
            if not birth_date_str.isdigit():
                raise ValueError("身份证中的出生日期部分包含非数字字符")
            birth_date = datetime.strptime(birth_date_str, '%Y%m%d').date()
            today = datetime.today().date()
            age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day))
            return age
        except ValueError as e:
            # 如果解析日期时发生错误，返回错误消息或适当的默认值
            messagebox.showerror("错误", f"无法解析出生日期: {e}")
            return ""  # 或者返回一个默认值，如 "未知"
        
    def safe_join(self, values):
        
        return ''.join(str(self.safe_value(v)) for v in values)
 
    def safe_value(self, value):
        
        if isinstance(value, list):
            return ''.join(map(str, value))
        return str(value)


    def search(self, search_text):
        # 在数据库中搜索匹配的记录
        # 假设db.all()返回的是一个包含记录的列表，每个记录都是一个字典
        results = [
            record for record in self.all()
            if search_text.lower() in self.safe_join(record.values()).lower()
        ]
        return results
 
    def create(self,volunteers):
        self.volunteers.append(volunteers)
    # def insert_search(self, archive_id):
    #     for volunteer in self.volunteers:
    #         if volunteer.get('archive_id') == archive_id:
    #             return volunteer
    #     return False
    # def insert_update(self):
    #     max_header_id = max(int(k.split('header_id')[-1]) for k in self.volunteers if k.startswith('header_id')) if self.volunteers else 0
    #     for i, header_id in enumerate(header_id, start=max_header_id + 1):
    #         self.volunteers[f'header_id{i}'] = [header_id] 
        



    


    

db =MysqlDatabases()


